package cn.wit.summit.chwan.ui.base;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.res.Configuration;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.support.v7.app.AppCompatActivity;
import android.text.Html;
import android.text.TextUtils;
import android.view.MotionEvent;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.TextView;
import android.widget.Toast;

import org.greenrobot.eventbus.EventBus;

import java.io.File;
import java.util.List;

import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.Stat.StatFactory;
import cn.wit.summit.chwan.interfaces.NetChangeInterface;
import cn.wit.summit.chwan.models.db.DownLoadTaskTable;
import cn.wit.summit.chwan.models.dbmanager.DownloadTaskManager;
import cn.wit.summit.chwan.tools.downloadtool.DownLoadStatusConfig;
import cn.wit.summit.chwan.tools.downloadtool.DownloadTool;
import cn.wit.summit.chwan.ui.activity.CommentAllListActivity;
import cn.wit.summit.chwan.ui.activity.CommentCreatActivity;
import cn.wit.summit.chwan.ui.activity.CommentDetailActivity;
import cn.wit.summit.chwan.ui.activity.GameDetailV2Activity;
import cn.wit.summit.chwan.ui.activity.LoginV2Activity;
import cn.wit.summit.chwan.ui.activity.MainLoginActivity;
import cn.wit.summit.chwan.ui.activity.SplashActivity;
import cn.wit.summit.chwan.utils.APKUtils;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.PreferenceUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.UtilsMy;
import cn.wit.summit.chwan.widgets.BaseAddEnergyDialog;
import cn.wit.summit.chwan.widgets.CurrencyPromptDialog;
import cn.wit.summit.chwan.widgets.LoginGuideDialog;
import cn.wit.summit.chwan.widgets.WaitingDialog;

/**
 * 描述
 * 作者 tangbingliang
 * 时间 16/6/28 15:33
 * 邮箱 bltang@atman.com
 * 电话 18578909061
 */
public class BaseAppCompatActivity extends AppCompatActivity implements NetChangeInterface {

    public WaitingDialog mWaitingDialog = null;
    private static long lastClickTime = 0;
    //应用是否销毁标志
    protected boolean isDestroy;
    private Toast mToast;

    protected Context mContext;
    protected Activity mAty;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        requestWindowFeature(Window.FEATURE_NO_TITLE);//隐藏bar
        super.onCreate(savedInstanceState);
        isDestroy = false;
        mAty = this;
        mContext = this;
        isDestroy = false;
        // 添加Activity到堆栈
        AppManager.getAppManager().addActivity(this);


    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
    }

    @Override
    public void startActivity(Intent intent) {
        super.startActivity(intent);
        overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    @Override
    protected void onPostResume() {
        super.onPostResume();
        if (!(mAty instanceof SplashActivity) && !(mAty instanceof LoginV2Activity)
                && AccountUtil.getInstance().getAccountData()==null) {
            IntentUtil.getInstance().goLoginActivity(mAty);
        }
    }

    @SuppressLint("RestrictedApi")
    @Override
    public void startActivityForResult(Intent intent, int requestCode, Bundle options) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            super.startActivityForResult(intent, requestCode, options);
        } else {
            super.startActivityForResult(intent, requestCode);
        }
        overridePendingTransition(R.anim.slide_right_in, R.anim.slide_left_out);
    }

    @Override
    protected void onResume() {
        super.onResume();
        updateAndroidApp();
    }

    protected void updateAndroidApp() {
        try {
            List<DownLoadTaskTable> staydownloadTasks = DownloadTaskManager.getInstance().findAllStayInstalledDownloadTask();
            List<DownLoadTaskTable> installeddownloadTasks = DownloadTaskManager.getInstance().findAllInstalledDownloadTask();
            List<DownLoadTaskTable> installingdownloadTasks = DownloadTaskManager.getInstance().findAllStayInstallingDownloadTask();
            for (DownLoadTaskTable downloadTask : installingdownloadTasks) {
                boolean hasinstal = APKUtils.getInstance(this).checkInstall(this, downloadTask.getPackageName());
                if (!hasinstal) {
                    downloadTask.setDownStatus(DownLoadStatusConfig.INSTALL_WAIT);
                    if (!StringUtils.isEmpty(downloadTask.getPackageName()))
                        DownloadTaskManager.getInstance().updateStatusByPackageName(downloadTask.getPackageName(), DownLoadStatusConfig.INSTALL_WAIT);
                    StatFactory.getInstance().sendGameInstall(mContext,downloadTask.getGameId(),2+"");
                    EventBus.getDefault().post(downloadTask.getDownEvent());
                }
            }
            for (DownLoadTaskTable downloadTask : staydownloadTasks) {
                boolean hasinstal = APKUtils.getInstance(this).checkInstall(this, downloadTask.getPackageName());
                if (hasinstal) {
                    APKUtils.APKInfo apkInfo = APKUtils.getInstance(this).getInstallAPKInfo(this, downloadTask.getPackageName());
                    if (apkInfo != null) {
                        if (apkInfo.getVersionCode() == downloadTask.getVer()) {
                            if (downloadTask != null) {
                                downloadTask.setDownStatus(DownLoadStatusConfig.INSTALLED);
                                DownloadTaskManager.getInstance().updateStatusByPackageName(apkInfo.getPackageName(), DownLoadStatusConfig.INSTALLED);
                                StatFactory.getInstance().sendGameInstall(mContext,downloadTask.getGameId(),1+"");
                            }
                            EventBus.getDefault().post(downloadTask.getDownEvent());
                            //如果安装完成apk后删除apk包。
                            try {
                                File file = new File(downloadTask.getDownPath());
                                if (file.exists()) {
                                    UtilsMy.delete(file);
                                }
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }
                    }
                }
            }
            for (DownLoadTaskTable downloadTask : installeddownloadTasks) {
                boolean hasinstal = APKUtils.getInstance(this).checkInstall(this, downloadTask.getPackageName());
                if (!hasinstal) {
                    StatFactory.getInstance().sendGameInstall(mContext, downloadTask.getGameId(),4+"");
                    DownloadTool.deletTask(downloadTask);
                }
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 防止快速点击,启动多个同样的界面
     *
     * @return
     */
    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        if (ev.getAction() == MotionEvent.ACTION_DOWN) {
            if (isFastDoubleClick() && (this instanceof CommentCreatActivity)) {
                return true;
            }
        }
        return super.dispatchTouchEvent(ev);
    }

    /**
     * 防止快速点击,启动多个同样的界面
     *
     * @return
     */
    public boolean isFastDoubleClick() {
        long now = System.currentTimeMillis();
        long timeD = now - lastClickTime;
        lastClickTime = now;
        return timeD <= 500;
    }

    public int getStateBarHeight() {

        /**
         * 获取状态栏高度——方法1
         * */
        int statusBarHeight1 = -1;
        //获取status_bar_height资源的ID
        int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");
        if (resourceId > 0) {
            //根据资源ID获取响应的尺寸值
            statusBarHeight1 = getResources().getDimensionPixelSize(resourceId);
        }
        return statusBarHeight1;
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        int screenNum = getResources().getConfiguration().orientation;
        full(screenNum == 2);
    }

    public void full(boolean isFull) {//控制是否全屏显示
        if (isFull) {
            WindowManager.LayoutParams lp = getWindow().getAttributes();
            lp.flags |= WindowManager.LayoutParams.FLAG_FULLSCREEN;
            getWindow().setAttributes(lp);
            getWindow().addFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        } else {
            WindowManager.LayoutParams attr = getWindow().getAttributes();
            attr.flags &= (~WindowManager.LayoutParams.FLAG_FULLSCREEN);
            getWindow().setAttributes(attr);
            getWindow().clearFlags(WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS);
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        isDestroy = true;
        // 结束Activity&从堆栈中移除
        AppManager.getAppManager().finishActivity(this);
    }

    @Override
    public void finish() {
        super.finish();
        overridePendingTransition(R.anim.slide_left_in, R.anim.slide_right_out);
    }

    public void exitApp() {
        AppManager.getAppManager().AppExit(this);
    }

    /**
     * 开启加载Loading
     */
    public void showLoading(String str) {
        showLoading(str, true);
    }

    public void ReShowLoading(String str) {
        if (mWaitingDialog != null) {
            mWaitingDialog.changeStatusStr(str);
        }
    }

    public void showLoading(String str, boolean isCancelable) {
        if (mWaitingDialog == null) {
            mWaitingDialog = new WaitingDialog(this, str);
        }
        mWaitingDialog.setCanceledOnTouchOutside(isCancelable);
        mWaitingDialog.startAnimation();
        mWaitingDialog.setCancelable(isCancelable);
        if (mWaitingDialog.isShowing()) {
            return;
        }
        if (!isFinishing()) {
            try {
                mWaitingDialog.show();
            } catch (Exception e) {

            }
        }
    }

    /**
     * 关闭加载Loading
     */
    public void cancelLoadingFinish() {
        cancelLoadingStstus(WaitingDialog.STATUS_FINISH);
    }

    public void cancelLoadingError() {
        cancelLoadingStstus(WaitingDialog.STATUS_ERROR);
    }

    public void cancelLoadingNetError() {
        cancelLoadingStstus(WaitingDialog.STATUS_NET_ERROR);
    }

    private void cancelLoadingStstus(int status) {
        try {
            if (mWaitingDialog != null && mWaitingDialog.isShowing()) {
                mWaitingDialog.changeStatus(status);
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        cancelLoading();
                    }
                }, 1000);
            }
        } catch (Exception e) {
        }
    }

    public void cancelLoading() {
        try {
            if (mWaitingDialog != null && mWaitingDialog.isShowing()) {
                mWaitingDialog.stopAnimation();
                mWaitingDialog.dismiss();
            }
        } catch (Exception e) {
        }
    }

    public void showToast(String text) {
        if (!TextUtils.isEmpty(text))
            showToast(text, Toast.LENGTH_SHORT);
    }

    public void showToast(String text, int time) {
        if (StringUtils.isEmpty(text))
            return;
        if (mToast == null) {
            mToast = Toast.makeText(getApplicationContext(), text, time);
        } else {
            mToast.setText(text);
            mToast.setDuration(Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

    public void cancelToast() {
        if (mToast != null) {
            mToast.cancel();
        }
    }

    public void onBackPressed() {
        cancelToast();
        super.onBackPressed();
    }

    //隐藏软键盘输入
    public void hideSoftInput(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
        }
    }

    //显示软键盘输入
    public void showSoftInput(View view) {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        if (imm != null) {
            view.requestFocus();
            imm.showSoftInput(view, 0);
        }
    }

    public boolean isOpenSoftInput() {
        InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
        return imm.isActive();//isOpen若返回true，则表示输入法打开
    }

    @Override
    public void reGetData() {
    }

    protected boolean isTopActivity() {
        boolean isTop = false;
        ActivityManager am = (ActivityManager) getSystemService(ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        LogUtils.e("cn.getClassName():" + cn.getClassName());
        LogUtils.e("cn.getClassName():" + mAty.getLocalClassName());
        if (cn.getClassName().contains(mAty.getLocalClassName())) {
            isTop = true;
        }
        return isTop;
    }
    LoginGuideDialog dialogGuid = null;

    public void showEnergyDialog(int num) {
//        if (isTopActivity() && num>0) {
//            showAddEnergyDialog(num);
//        }
    }

    public void showEnergyDialogByTrue(int num) {
//        if (num>0) {
//            showAddEnergyDialog(num);
//        }
    }

    private void showAddEnergyDialog(int num){
        if (MyApplication.accountBean == null || MyApplication.accountBean.getUid() == 0) {
            if (!PreferenceUtil.getBoolPreferences(this, "notfirstShowEnnergyDialog") ) {

                if (dialogGuid != null) {
                    dialogGuid.dismiss();
                    dialogGuid = null;
                }
                dialogGuid = new LoginGuideDialog(this);
                dialogGuid.show();

                dialogGuid.setOkBtn(new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PreferenceUtil.saveBoolPreference(v.getContext(), "notfirstShowEnnergyDialog", true);
                        IntentUtil.getInstance().goLoginActivity(v.getContext());
//                        Intent intent = new Intent(v.getContext(), MainLoginActivity.class);
//                        v.getContext().startActivity(intent);
                        dialogGuid.dismiss();
                    }
                });
                dialogGuid.setCancleBtn( new View.OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        PreferenceUtil.saveBoolPreference(v.getContext(), "notfirstShowEnnergyDialog", true);
                        dialogGuid.dismiss();
                    }
                });

                return;
            }
        }
//        if (dialog != null) {
//            dialog.dismiss();
//            dialog = null;
//        }
//        dialog = new BaseAddEnergyDialog(mContext);
//        if (!mAty.isFinishing() && !dialog.isShowing()) {
//            dialog.show();
//            dialog.setEnergyNum(num);
//            new Handler().postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    if (dialog != null)
//                        dialog.dismiss();
//                }
//            }, 2000);
//        }
    }
}
